<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=0">
  <link rel="stylesheet" href="./style/common.css">
  <title>云手机HOST</title>
  <style>
    .login-content {
      border: 1px solid #DFE1E6;
    }
    @media screen and (max-width: 768px) {
      .login-content {
        width: 100%;
        height: 100%;
      }
      .input-login {
        width: 300px;
        height: 340px;
      }
    }
  </style>
</head>
<body>
  <div class="container">
    <div class="login-content" id="loginContent">
      <div class="input-login" id="inputLogin">
        <div class="login-title" id="testPageEntrance">LOGIN</div>
        <div class="input-item">
          <div class="focus-title focus-login-title" id="focusName">Name</div>
          <input placeholder="Name" type="text" id="usernameInput" name="usernameInput"
            class="input-value input-login-value" onfocus="hidePlaceholder('usernameInput', 'focusName')" onblur="showPlaceholder('usernameInput', 'focusName')">
        </div>
        <div class="input-item">
          <div class="focus-title focus-login-title" id="focusPassword">Password</div>
          <input placeholder="Password" type="text" id="passwordInput" name="passwordInput"
            class="input-value input-login-value" onfocus="hidePlaceholder('passwordInput', 'focusPassword')" onblur="showPlaceholder('passwordInput', 'focusPassword')">
        </div>
        <div class="input-item text-align">
          <button type="button" id="loginBtn" class="input-login-btn" onclick="login()">LOGIN</button>
        </div>
      </div>
    </div>
  </div>

  <div class="message-content" id="messageContent">
    <div class="message-modal">
      <div class="header-content">
        <p>温馨提示</p>
      </div>
      <div class="body-content">
        <p class="msg" id="alertMsg"></p>
      </div>
    </div>
  </div>
  <script src="./common.js"></script>
  <script type="text/javascript">
    let commonParams = null;
    let lastClickTime = 0;
    const threshold = 500; // 阈值500ms
    let clickCount = 1; // 连续点击次数
    const channelType = {
      'socket': 'WebSocket',
      'rtc': 'WebRtc'
    };

    window.onload = function() {
      getInterfaceDomain();
      const testPageEntrance = document.getElementById('testPageEntrance');
      testPageEntrance.addEventListener('click', () => {
        const currentTime = new Date().getTime();
        if (currentTime - lastClickTime < threshold) {
          clickCount ++;
        } else {
          lastClickTime = 0;
          clickCount = 1;
        }

        lastClickTime = currentTime;
        // 连续点击次数等于5次
        if (clickCount === 5) {
          let localHref = window.location.href;
          if (window.location.href.indexOf('login.html') > -1) {
            localHref = window.location.href.replace('login.html',  'enter.html');
          } else if (window.location.href.indexOf('index') > -1) {
            localHref = window.location.href.replace('index',  'enter.html');
          } else {
            localHref += 'enter.html';
          }

          window.location.href = localHref;
          clickCount = 0;
        }
      });
    }

    function getInterfaceDomain() {
      let currentHref = window.location.href;
      let jsonFilePath = null;
      if (currentHref.indexOf('login.html') > -1) {
        jsonFilePath = currentHref.replace('login.html', 'common.json');
      } else {
        jsonFilePath = currentHref + 'common.json';
      }
      
      xhrHttpRequest('GET', jsonFilePath, null).then((res) => {
        commonParams = JSON.parse(res);
      }, error => {
        showResErrorMsg(error);
      });
    }

    function validate(usernameVal, passwordVal) {
      let isError = false;
      const commonTip = '请检查用户名和密码。';
      let nameTip = '';
      let passwordTip = '';
      if (usernameVal.length < 1 || usernameVal.length > 32) {
        nameTip = '请检查用户名。长度必须是1~32位';
        isError = true;
      }
      if (passwordVal.length < 6 || passwordVal.length > 32) {
        passwordTip = '请检查密码。长度必须是6~32位';
        isError = true;
      }

      let finalTip = '';
      if (nameTip && passwordTip) {
        finalTip = commonTip;
      } else if (nameTip && !passwordTip) {
        finalTip = nameTip;
      } else if (!nameTip && passwordTip) {
        finalTip = passwordTip;
      } else {
        finalTip = '';
      }

      if (finalTip) {
        showAlertModal(finalTip);
      }

      return isError;
    }

    function login() {
      const usernameInputEle = document.getElementById('usernameInput');
      const passwordInputEle = document.getElementById('passwordInput');
      const usernameVal = usernameInputEle.value;
      const passwordVal = passwordInputEle.value;
      const isError = validate(usernameVal, passwordVal);
      if (isError) {
        return;
      }

      const userInfo = {
          'username': usernameVal,
          'password': passwordVal
      }
      const userInfoJson = JSON.stringify(userInfo);
      const loginUrl = [commonParams.interfaceDomain, 'user/login'].join('/');
      xhrHttpRequest('POST', loginUrl, userInfoJson).then((res) => {
        if (sessionStorage.getItem('userInfo')) {
          sessionStorage.removeItem('userInfo');
          sessionStorage.setItem('userInfo', res);
        } else {
          sessionStorage.setItem('userInfo', res);
        }
        goPhonePage();
      }, error => {
        showResErrorMsg(error);
      });
    }

    function hidePlaceholder(elementId, focusId) {
      const inputEle = document.getElementById(elementId);
      const focusTitle = document.getElementById(focusId);
      if (inputEle.placeholder) {
        focusTitle.innerHTML = inputEle.placeholder;
        focusTitle.style.display = 'block';
        inputEle.removeAttribute('placeholder');
      }
    }

    function showPlaceholder(elementId, focusId) {
      const inputEle = document.getElementById(elementId);
      const focusTitle = document.getElementById(focusId);
      const placeholderStr = focusTitle.innerHTML;
      if (inputEle.value) {
        focusTitle.style.display = 'block';
        inputEle.removeAttribute('placeholder');
      } else {
        focusTitle.style.display = 'none';
        inputEle.setAttribute('placeholder', placeholderStr);
      }
    }

    function showResErrorMsg(responseStr) {
      if (!responseStr) {
        return;
      }
      const response = JSON.parse(responseStr);
      const message = response.errorMsg;
      showAlertModal(message);
    }

    function hideAlertModal() {
      const messageContent = document.getElementById('messageContent');
      setTimeout(() => {
        messageContent.style.display = 'none';
      }, 2000);
    }

    function showAlertModal(message) {
      const messageContent = document.getElementById('messageContent');
      const alertMsg = document.getElementById('alertMsg');
      alertMsg.innerHTML = message;
      messageContent.style.display = 'flex';

      hideAlertModal();
    }

    function goPhonePage() {
      // 获取手机列表，连接分配的云机
      getUserPhoneList();
    }

    function getUserPhoneList() {
      const userInfo = JSON.parse(sessionStorage.getItem('userInfo'));
      headerConfig = {
        'token': userInfo.token,
        'session_id': userInfo.session_id
      };
      const listUrl = [commonParams.interfaceDomain, 'phone/list'].join('/');
      xhrHttpRequest('POST', listUrl, null, headerConfig).then((res) => {
        const phoneList = JSON.parse(res);
        const phoneId = phoneList[0].phone_id;

        let localHref = window.location.href;
        if (window.location.href.indexOf('login.html') > -1) {
          localHref = window.location.href.replace('login.html',  'demo.html');
        } else {
          localHref = localHref + 'demo.html';
        }
        window.location.href = localHref + '?phone_id='+phoneId;
      }, error => {
        const errorConfig = JSON.parse(error);
        showAlertModal(errorConfig.errorMsg);
        setTimeout(() => {
          closeModal();
        },2000);
      });
    }

    function getPhoneInfo(phoneId) {
      const allocateUrl = [commonParams.interfaceDomain, 'connection/allocate'].join('/');
      const userInfo = JSON.parse(sessionStorage.getItem('userInfo'));
      const params = JSON.stringify({
        'phone_id': phoneId,
        'client_type': 'HTML5'
      });

      xhrHttpRequest('POST', allocateUrl, params, headerConfig).then((res) => {
        sessionStorage.setItem('phoneInfo', res);
        sessionStorage.setItem('channelType', channelType.socket);
      }, error => {
        const errorConfig = JSON.parse(error);
        showAlertModal(errorConfig.errorMsg);
        setTimeout(() => {
          closeModal();
        },2000);
      });
    }
  </script>
</body>
</html>